<?php

//require_once "manage/Wx.php";
require_once "core.php";
session_start();
/*error_reporting(0);*/
$code = $_REQUEST["code"];
$state = $_REQUEST["state"];

$appid = "wx6a26f16011095354";
$secret = "d007ae1d5fcd5d757684346b572a8d72";
$token=Get_access_token();

$ch = curl_init();//初始化curl


$postUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $secret . "&code=" . $code . "&grant_type=authorization_code";
curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
$result = curl_exec($ch);
$openId = json_decode($result)->openid;

/*$openId="otrc4sz3qPPvKvVayiShOGi9nysY";*/
$postUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $token . "&openid=" . $openId . "&lang=zh_CN";
curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
$result = curl_exec($ch);
$user = json_decode($result);
//var_export($user);
if ($user->subscribe == 1) {
    $_SESSION["user"] = $user->openid;
    $weixin_id=$_SESSION["user"];
    $user1 = $core->GetUserByWxId($weixin_id);
    /*$pdo = new PDO("mysql:host=ylhsdb.mysqldb.chinacloudapi.cn;dbname=ylhs_db;charset=utf8;charset=utf8","ylhsdb%lchroot","Password01!");
    $sql2=$pdo->prepare("delete FROM user WHERE id=:id");
    $sql2->execute(array("id"=>"50"));*/
    if(empty($user1)){
        $core->AddUser($weixin_id,null,null,$user->headimgurl,$user->nickname);
        $user1 = $core->GetUserByWxId($weixin_id);
    }
    header("location:/wap/index.php");
    echo $user->nickname;
    echo $user->sex;
    echo $user->city;
    echo $user->province;
    echo $user->country;
    echo $user->headimgurl;
} else {
    $state=rand(100000,999999);
    $ticket=GetTicket($state);
    echo '<div style="text-align: center;">';
    GetCodeImage($ticket);
    echo '</div>';
    echo "<div style='text-align: center;'>用户未关注公众号,请扫码关注</div>";
}
curl_close($ch);